package com.example.reggie.controller;

import com.example.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 老肥！！！
 * @Date: 2022/09/16/10:07
 * @Description: 不想学代码了！！！
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        使用UUID重新生成文件名，防止文件名重复覆盖
        String fileName=UUID.randomUUID().toString() + substring;
//      创建目录对象
        File dir = new File(basePath);
//        判断是否存在
        if(!dir.exists()){
//            不存在则创建新目录
            dir.mkdir();
        }
//        file是一个临时文件，需要转存到其他位置，否则本次请求完成后会删除
        log.info(file.toString());
        try{
            file.transferTo(new File(basePath+fileName));
        }catch (Exception e){
            e.printStackTrace();
        }
        return  R.success(fileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //        使用输入流读取文件内容

            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //        通过输出流输出文件内容写回浏览器上，在浏览器上显示
            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setContentType("/image/jpeg");
            int len = 0;
            byte[]bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                servletOutputStream.write(bytes,0,len);
                servletOutputStream.flush();
            }
//            关闭输入输出流
            fileInputStream.close();
            servletOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
